package com.zxy.leetcode._00000_00099._00030_00039;

/**
 * https://leetcode-cn.com/problems/search-insert-position/
 *
 * 搜索插入位置
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。
 * 如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * 你可以假设数组中无重复元素。
 */
public class Test00035 {

    public static void main(String[] args) {
        Test00035 test = new Test00035();
        int[] nums = {3, 5, 7, 9, 10, 11};
        System.out.println(test.searchInsert(nums, 9));
    }

    public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        if (nums[0] >= target) {
            return 0;
        }
        if (nums[nums.length - 1] == target) {
            return nums.length - 1;
        }
        if (nums[nums.length - 1] < target) {
            return nums.length;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            if (right - left == 1) {
                break;
            }
            if (nums[mid] > target) {
                right = mid - 1;
            }else {
                left = mid + 1;
            }
        }

        // 走到这里，right - left == 1 OR left == right
        if (nums[left] == target) {
            return left;
        }
        if (nums[right] == target) {
            return right;
        }
        if (nums[right] < target && nums[left] < target) {
            return Math.max(left, right) + 1;
        }
        if (nums[right] > target && nums[left] > target) {
            return Math.min(left, right);
        }

        return left + 1;
    }

    /*
    https://leetcode-cn.com/problems/search-insert-position/solution/hua-jie-suan-fa-35-sou-suo-cha-ru-wei-zhi-by-guanp/
     */
    public int searchInsert2(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while(left <= right) {
            int mid = (left + right) / 2;
            if(nums[mid] == target) {
                return mid;
            } else if(nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }

}
